package com.qianchang.microfinance.view.credit.data;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FileUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.bean.event.AgreementTitleBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.utils.SpanUtils;
import com.qianchang.microfinance.utils.UUIDS;
import com.qianchang.microfinance.view.hsfaceidentity.ResultActivity;
import com.qianchang.microfinance.view.register.AgreementActivity;
import com.qianchang.microfinance.view.register.AgreementApi;
import com.lzy.imagepicker.bean.ImageItem;
import com.megvii.idcardquality.IDCardQualityLicenseManager;
import com.megvii.licensemanager.Manager;
import com.megvii.livenessdetection.Detector;
import com.megvii.livenessdetection.LivenessLicenseManager;
import com.megvii.livenesslib.LivenessActivity;
import com.megvii.livenesslib.util.ConUtil;
import com.megvii.livenesslib.util.SharedUtil;
import com.tencent.faceid.FaceIdClient;
import com.tencent.faceid.model.GetLipLanguageRequest;
import com.tencent.faceid.model.GetLipLanguageResult;
import com.tencent.faceid.model.VideoIdCardIdentityRequest;
import com.tencent.faceid.model.VideoIdCardIdentityResult;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.FaceRecordBean;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.ImageChoseActivity;
import com.qianchang.microfinance.view.credit.data.common.FaceIdHelper;
import com.qianchang.microfinance.view.credit.data.facerecoder.FaceVideoRecordActivity;
import com.qianchang.microfinance.view.dialog.alert.DimengSingleButtonAlertDialog;

import org.json.JSONArray;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class ScanFaceActivity extends ImageChoseActivity {

    private static final String TAG = "ScanFaceActivity";
    public static final String VALIDATE_DATA = "validate_data";
    public static final int REQUEST_SCAN_FACE = 102;

    private String validateData;
    private String imagePath;

    private FaceIdClient faceIdClient;
    private String bucket;
    private String sign;
    private String idCard;
    private String realName;
    private String videoPath;

    private static final int STATUES_TAKE_PHOTO = 0;
    private static final int STATUES_TAKE_VIDEO = 1;

    private static final int REG_FACE_RESPONSE = 1; //人脸识别成功
    private static final int REG_FACE_ERROR = 2;     //人脸识别失败
    private static final int GET_LIP_SUCCESS = 3;    //唇语识别成功
    private static final int GET_LIP_ERROR = 4;       //唇语识别失败


    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @BindView(R.id.btn_face_commit)
    TextView btnFaceCommit;
    @BindView(R.id.ll_face_scan)
    LinearLayout llFaceScan;
    @BindView(R.id.iv_face)
    ImageView ivFace;
    @BindView(R.id.ll_take_video)
    LinearLayout llTakeVideo;
    @BindView(R.id.tv_tip_photo)
    DTextView tvTipPhoto;
    @BindView(R.id.tv_protocol)
    DTextView tvProtocol;

    private GetLipLanguageResult lipLanguage;
    private SharedUtil mSharedUtil;
    private boolean isConfirml = false;



    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            dismiss();
            switch (msg.what) {
                case REG_FACE_RESPONSE:
                    dealRecognizeResult(msg);
                    break;
                case REG_FACE_ERROR:
                    onFailed(getString(R.string.recoglise_face_failed));
                    break;
                case GET_LIP_SUCCESS:
                    getVideo();
                    break;
                case GET_LIP_ERROR:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_face);
        ButterKnife.bind(this);
        AgreementData();

        initView();
        initData();
        iniths();

    }

    public boolean isConfirml() {
        return isConfirml;
    }

    public void setConfirml(boolean confirml) {
        isConfirml = confirml;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitleName(getString(R.string.label_face_photo));
        setMaxImageCount(1);

        Bundle bundle = getBundle();
        if(bundle != null){
            isConfirml = bundle.getBoolean("isConfirml",false);
        }else {
            isConfirml = false;
        }

    }

    @Override
    protected void initData() {
        super.initData();
        setViewStatue(STATUES_TAKE_PHOTO);
        getExecuteSignInterface();
        FaceIdHelper faceIdHelper = FaceIdHelper.getInstance(this);
        faceIdClient = faceIdHelper.getFaceIdClient();
    }

    @Override
    protected void onResume() {
        super.onResume();

        String language_save = mSharedUtil.getStringValueByKey("language");
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (!language.equals(language_save))
            showLanguage(language);
    }


    /**
     * 处理认证结果
     *
     * @param msg 结果显示的信息
     */
    private void dealRecognizeResult(Message msg) {
        VideoIdCardIdentityResult videoIdCardIdentityResult = (VideoIdCardIdentityResult) msg.obj;
        if (null != videoIdCardIdentityResult) {
            int code = videoIdCardIdentityResult.getCode();
            //相似度大于80才是识别成功
            if (code == 0 && videoIdCardIdentityResult.getCompareStatus() == 0 && videoIdCardIdentityResult.getLiveStatus() == 0 && videoIdCardIdentityResult.getSimilarity() > 60) {
                startVerifyIdNumber();
            } else {
                onFailed(getString(R.string.recoglise_face_failed));
            }
            DMLog.e(TAG, "handleMessage: " + videoIdCardIdentityResult.toString());
        }
    }

    /**
     * 获取视频文件
     */
    private void getVideo() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (null != lipLanguage) {
                    validateData = lipLanguage.getValidateData();
                    Bundle bundle = new Bundle();
                    bundle.putString(VALIDATE_DATA, validateData);
                    startActivityForResult(FaceVideoRecordActivity.class, bundle, REQUEST_SCAN_FACE);//未进行实名认证，点击 人脸识别、银行卡信息，提示“请先完成实名认证”；
                } else {
                    ToastUtil.getInstant().show(ScanFaceActivity.this, "获取唇语失败");
                }
            }

            @Override
            public void permissionSomeDeny() {
            }
        }, "", PERMISSIONS);
    }

    /**
     * 认证成功
     */
    public void onSuccess() {
        DimengSingleButtonAlertDialog singleButtonAlertDialog = DimengSingleButtonAlertDialog.newInstance("", "人脸识别成功");
        singleButtonAlertDialog.setOnDialogClickListener(new DimengSingleButtonAlertDialog.OnDialogClickListener() {
            @Override
            public void agree() {
                if (null != imagePath) {
                    FileUtils.deleteFile(imagePath);
                }
                if (null != videoPath) {
                    FileUtils.deleteFile(videoPath);
                }
                finish();
            }
        });
        singleButtonAlertDialog.setAgreeText(getString(R.string.confirm));
        singleButtonAlertDialog.show(getSupportFragmentManager(), getClass().getSimpleName());
    }

    /**
     * 认证失败
     */
    public void onFailed(String msg) {
        DimengSingleButtonAlertDialog singleButtonAlertDialog = DimengSingleButtonAlertDialog.newInstance("", msg);
        singleButtonAlertDialog.setOnDialogClickListener(new DimengSingleButtonAlertDialog.OnDialogClickListener() {
            @Override
            public void agree() {

                setViewStatue(STATUES_TAKE_PHOTO);
                if (null != imagePath) {
                    FileUtils.deleteFile(imagePath);
                }
                if (null != videoPath) {
                    FileUtils.deleteFile(videoPath);
                }
            }
        });
        singleButtonAlertDialog.setAgreeText(getString(R.string.confirm));
        singleButtonAlertDialog.show(getSupportFragmentManager(), getClass().getSimpleName());
    }


    protected void showLanguage(String language) {
        // 设置应用语言类
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        if (language.equals("zh")) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            config.locale = Locale.ENGLISH;
        }
        resources.updateConfiguration(config, dm);
        mSharedUtil.saveStringValue("language", language);
        freshView();
    }

    private void freshView() {
        Intent intent = new Intent(this, ScanFaceActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }



    @OnClick({R.id.ll_face_scan, R.id.btn_face_commit})
    public void onViewClicked(View view) {
        if (checkClick(view.getId())) {
            switch (view.getId()) {
//                case R.id.ll_face_scan:
//                    initImagePickerForTakePhoto();
//                    Intent intent = new Intent(this, ImageGridActivity.class);
//                    intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
//                    startActivityForResult(intent, REQUEST_CODE_SELECT);
//                    break;
                case R.id.ll_face_scan:
//                    getLipText();             //2018.1.12注释掉迪蒙代码

                    /*****
                     * 鸿胜科技新增加 2018.1.12
                     */

                    netWorkWarranty();

                    break;
            }
        }
    }

    /**
     * 获取唇语
     */
    private void getLipText() {
        show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    GetLipLanguageRequest getLipLanguageRequest = new GetLipLanguageRequest(bucket);
                    getLipLanguageRequest.setSign(sign);
                    lipLanguage = faceIdClient.getLipLanguage(getLipLanguageRequest);
                    Message message = handler.obtainMessage(GET_LIP_SUCCESS);
                    handler.sendMessage(message);
                } catch (Exception e) {
                    ToastUtil.getInstant().show(ScanFaceActivity.this, "获取唇语失败");
                    e.printStackTrace();
                    Message message = handler.obtainMessage(GET_LIP_ERROR);
                    handler.sendMessage(message);
                }
            }
        }).start();
    }


    @Override
    public void onPhotoResult(ArrayList<ImageItem> imageItems, int flag) {
        if (null != imageItems && imageItems.size() > 0) {
            imagePath = imageItems.get(0).getPath();
            setViewStatue(STATUES_TAKE_VIDEO);
        } else {
            setViewStatue(STATUES_TAKE_PHOTO);
        }
        clearSelectImages();
    }

    /**
     * 开始识别
     */
    private void startVerifyFace() {
        File file = new File(videoPath);
        if (file.exists()) {
            show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        VideoIdCardIdentityRequest videoImageIdentityRequest = new VideoIdCardIdentityRequest(bucket, validateData, videoPath, idCard, realName
                                , "seqStr");
                        videoImageIdentityRequest.setSign(sign);
                        VideoIdCardIdentityResult videoImageIdentityResult = faceIdClient.videoIdCardIdentity(videoImageIdentityRequest);
                        Message message = handler.obtainMessage(REG_FACE_RESPONSE);
                        message.obj = videoImageIdentityResult;
                        handler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Message message = handler.obtainMessage(REG_FACE_ERROR);
                        handler.sendMessage(message);
                    }
                }
            }).start();
        }
    }

    /**
     * 获取配置信息
     */
    private void getExecuteSignInterface() {
        show();
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.EXECUTE_SIGNIN_TERFACE, params, new RequestCallBack<FaceRecordBean>() {
            @Override
            public void onSuccess(JsonResult<FaceRecordBean> response) {
                dismiss();
                if (response.isReqDataSuccess()) {
                    FaceRecordBean faceRecordBean = response.getObject();
                    if (null != faceRecordBean) {
                        idCard = faceRecordBean.getIdCard();
                        realName = faceRecordBean.getRealName();
                        sign = faceRecordBean.getSign();
                        bucket = faceRecordBean.getAppId();
                    }
                } else {
                    ToastUtil.getInstant().show(ScanFaceActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ScanFaceActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }



    /**
     * 设置界面显示状态
     *
     * @param statue 成功失败的状态
     */
    public void setViewStatue(int statue) {
        switch (statue) {
            case STATUES_TAKE_PHOTO:
                setTitleName("人脸拍摄");
                llTakeVideo.setVisibility(View.GONE);
                tvTipPhoto.setVisibility(View.VISIBLE);
                llFaceScan.setVisibility(View.VISIBLE);
                imagePath = null;
                videoPath = null;
                break;
            case STATUES_TAKE_VIDEO:
                setTitleName("人脸识别");
                if (TextUtils.isEmpty(imagePath)) {
                    llTakeVideo.setVisibility(View.GONE);
                    tvTipPhoto.setVisibility(View.VISIBLE);
                    llFaceScan.setVisibility(View.VISIBLE);
                } else {
                    llTakeVideo.setVisibility(View.VISIBLE);
                    tvTipPhoto.setVisibility(View.GONE);
                    llFaceScan.setVisibility(View.GONE);
                    btnFaceCommit.setText("视频拍摄");
                }
                break;
        }
        Glide.with(ScanFaceActivity.this).load(imagePath).error(R.drawable.bg_rlpz).into(ivFace);
    }


    /**
     * 提交认证结果
     */
    private void startVerifyIdNumber() {
        HttpParams params = new HttpParams();
        params.put("faceRecogniteResult", "1");
        show();
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.UPDATE_FACE_RECOGNIT_ERESULT, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ScanFaceActivity.this.onSuccess();
                } else {
                    ToastUtil.getInstant().show(ScanFaceActivity.this, response.getDescription());
                    onFailed(response.getDescription() + "，请重新认证！");
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                onFailed(msg + "，请重新认证！");
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }


    /***********************************************
     *  鸿胜科技新增以下代码
     *  2018.1.12
     * ********************************************/

    private String uuid;

    private void iniths() {
        mSharedUtil = new SharedUtil(this);
        uuid = ConUtil.getUUIDString(this);
    }

    private void netWorkWarranty() {
        show("联网授权中....");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Manager manager = new Manager(ScanFaceActivity.this);
                LivenessLicenseManager licenseManager = new LivenessLicenseManager(ScanFaceActivity.this);
                manager.registerLicenseManager(licenseManager);

                manager.takeLicenseFromNetwork(uuid);
                if (licenseManager.checkCachedLicense() > 0)
                    mHandler.sendEmptyMessage(1);
                else
                    mHandler.sendEmptyMessage(2);
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            dismiss();
            switch (msg.what) {
                case 1:                 //联网授权成功
                    enterNextPage();

                    break;
                case 2:                 //联网授权失败
                    ToastUtil.getInstant().show(ScanFaceActivity.this,"联网授权失败！请检查网络或找服务商");
                    break;
            }
        }
    };



    private static final int PAGE_INTO_LIVENESS = 100;

    private void enterNextPage() {
        startActivityForResult(new Intent(this, LivenessActivity.class), PAGE_INTO_LIVENESS);
    }


    private static final int FINSH_CODE = 1001;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SCAN_FACE) {
            if (resultCode == RESULT_OK && null != data) {
                videoPath = data.getStringExtra(FaceVideoRecordActivity.VIDEO_PATH);
                if (null != videoPath) {
                    startVerifyFace();
                }
            }
        }

        if (requestCode == FINSH_CODE && resultCode == RESULT_OK) {
            ScanFaceActivity.this.finish();
        }

        if (requestCode == PAGE_INTO_LIVENESS && resultCode == RESULT_OK) {
            String result = data.getStringExtra("result");
            String delta = data.getStringExtra("delta");
            Serializable images=data.getSerializableExtra("images");
            Bundle bundle = data.getExtras();
            bundle.putBoolean("isConfirml",isConfirml);
            startActivityForResult(ResultActivity.class,bundle,FINSH_CODE);
        }

    }


    //获取协议内容
    private void AgreementData(){

        JSONArray js = new JSONArray();
        js.put("10");

        AgreementApi.getAgreementName(this, js, new AgreementApi.AgreementNameCallBack() {
            @Override
            public void success(List<AgreementTitleBean> agreementName) {
                if (null != agreementName && !agreementName.isEmpty()) {

                    tvProtocol.setMovementMethod(LinkMovementMethod.getInstance());
                    tvProtocol.setHighlightColor(getResources().getColor(android.R.color.transparent));
                    SpanUtils spanUtils = new SpanUtils();
                    spanUtils.append(getString(R.string.Label_reading)).setForegroundColor(getResources().getColor(R.color.common_black_color_6)).append("《" + agreementName.get(0).getAgreementName() + "》").setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View view) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "10");
                            startActivity(AgreementActivity.class, bundle);
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            ds.setColor(getResources().getColor(R.color.common_blue_color_light));
                            ds.setUnderlineText(false);
                        }
                    });

                    tvProtocol.setText(spanUtils.create());
                }
            }
        });
    }




}
